package com.project.quiktask.controller;

import java.sql.Date;
import java.sql.Time;
import java.util.Comparator;

import com.project.quiktask.Task;
import com.project.quiktask.util.Variable;

public class TimeComparator implements Comparator<Task> {    

	Date taskOneEarlierDate;
	Time taskOneEarlierTime;
	Date taskTwoEarlierDate;
	Time taskTwoEarlierTime;

	public int compare(Task taskOne, Task taskTwo) {

		Date taskOneStartDate = taskOne.getStartDate();
		Date taskOneDeadlineDate = taskOne.getDeadlineDate();
		Time taskOneStartTime = taskOne.getStartTime();
		Time taskOneDeadlineTime = taskOne.getDeadlineTime();

		Date taskTwoStartDate = taskTwo.getStartDate();
		Date taskTwoDeadlineDate = taskTwo.getDeadlineDate();
		Time taskTwoStartTime = taskTwo.getStartTime();
		Time taskTwoDeadlineTime = taskTwo.getDeadlineTime();

		int result;

		// TODO refactor this!
		result = getEarlierDateAndTimeOfTask(taskOneStartDate, taskOneDeadlineDate, taskOneStartTime, taskOneDeadlineTime);
		
		if (result < 0) {
			taskOneEarlierDate = taskOneStartDate;
			taskOneEarlierTime = taskOneStartTime;
		} else {
			taskOneEarlierDate = taskOneDeadlineDate;
			taskOneEarlierTime = taskOneDeadlineTime;
		}

		result = getEarlierDateAndTimeOfTask(taskTwoStartDate, taskTwoDeadlineDate, taskTwoStartTime,
				taskTwoDeadlineTime);

		if (result < 0) {
			taskTwoEarlierDate = taskTwoStartDate;
			taskTwoEarlierTime = taskTwoStartTime;
		} else {
			taskTwoEarlierDate = taskTwoDeadlineDate;
			taskTwoEarlierTime = taskTwoDeadlineTime;
		}

		result = getMoreUrgentTask();

		return result; 
	}

	public int getEarlierDateAndTimeOfTask (Date date1, Date date2, Time time1, Time time2) {
		int result;

		if (isDateNull(date1) && !isDateNull(date2))
			return Variable.SECOND_TASK_MORE_URGENT;
		else if (!isDateNull(date1) && isDateNull(date2))
			return Variable.FIRST_TASK_MORE_URGENT;
		else {
			result = date1.compareTo(date2);
			if (result != Variable.EQUAL_URGENCY)
				return result;
			else {
				if (isTimeNull(time1) && !isTimeNull(time2)) 
					return Variable.SECOND_TASK_MORE_URGENT;
				else if (!isTimeNull(time1) && isTimeNull(time2))
					return Variable.FIRST_TASK_MORE_URGENT;
				else {
					result = time1.compareTo(time2);
					if (result < Variable.EQUAL_URGENCY)
						return Variable.FIRST_TASK_MORE_URGENT;
					else
						return Variable.SECOND_TASK_MORE_URGENT;
				}
			}
		}
	}


	public int getMoreUrgentTask() {
		int result = taskOneEarlierDate.compareTo(taskTwoEarlierDate);
		if (result == Variable.EQUAL_URGENCY)
			result = taskOneEarlierTime.compareTo(taskTwoEarlierTime);
		return result;
	}

	public boolean isDateNull(Date date) {
		if (date == null)
			return true;
		else 
			return false;
	}

	public boolean isTimeNull(Time time) {
		if (time==null)
			return true;
		else
			return false;
	}
}